/**
 * Created by lx on 2018/4/3.
 */
CommonUtils.regNamespace("com.im.moneyPlaneManage.moneyApply");

$(function() {
    com.im.moneyPlaneManage.moneyApply.invoke.init();
});

com.im.moneyPlaneManage.moneyApply.invoke = function() {
    var client = new com.im.common.ajax();

    /**
     * 页面初始化
     * @private
     */
    function _init() {
        //初始化时间、复选框、下拉框等事件和样式
        _initCommpentAction();
        //表单验证初始化
        _initFormValidate();
        //资金计划列表查询
        $("#vQueryMoneys").on("click", function () {
            _queryMoneys(1);
        }).trigger("click");
        //条件重置
        $("#vResetCond").on("click", _resetCond);
        //资金计划申报
        $("#vShowAddMoney").on("click", _showAddMoney);
        //资金计划申报
        $("#vAddApply").on("click", _addApply);
        //时间插件
        $('#yearDt').datepicker({
            startView: 'decade',
            minView: 'decade',
            format: 'yyyy',
            maxViewMode: 2,
            minViewMode:2,
            autoclose: true
        });
        $('#endDt').datepicker({
            todayHighlight:true,
            todayBtn: 'linked',
            keyboardNavigation:true,
            autoclose:true,
            language:'zh-CN',
            format:'yyyy-mm-dd'
        });

        //批量时间
        $("#batchOpenBtn").click(function () {
            _batchOper('10');
        });
        $("#batchCloseBtn").click(function () {
            _batchOper('20');
        })
    }
    function _batchOper(type){
        var checkedItems = $('#vMoneyTable').datagrid('getChecked');

        var olist = [];
        $.each(checkedItems,function (i,obj) {
            //开放，且为关闭状态
            if(type ==  '10' && obj.statusCd == '20'){
                olist.push(obj.declareSetId);
            }
            //关闭，且为开发状态
            if(type ==  '20' && obj.statusCd == '10'){
                olist.push(obj.declareSetId);
            }
        });

        if(olist.length > 0){
            var param = {};
            param.declareSetIds = olist;
            param.statusCd = type;

            var result = client.callAsJson("fundPlanService/updateFundPlanDeclareSet", param);
            if(result.resultCode=='0'){

                toastr.success("操作成功！");
                _queryMoneys(1);
            }else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        }else{
            toastr.success("操作成功！");
        }
    }

    function _initCommpentAction() {
        //时间插件
        $('#startDatepicker,#endDatepicker').datepicker({
            autoclose: true
        });
        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();

        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal1' ></div>")));
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal2' ></div>")));
        $("#vQuerySubject").click(function() {
            $("#vQuerySubject").itemSearchCommpent({
                elmIdOut : "vSubjectName2",//组织树单击之后回填的文本框（input）
                elmIdModal : "modal1",//用户选择
                elmIdOrgModal : "modal2",//组织查询
                callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
                    $("#vSubjectName2").attr("vaSubjectId", projectId);
                    $('#vAddApplyForm').data('bootstrapValidator').updateStatus('vSubjectName2', 'NOT_VALIDATED',null).validateField('vSubjectName2');
                }
            });
        });
    }

    /**
     * 表单验证
     * @param $form
     * @returns {boolean}
     * @private
     */
    function _formValidate($form) {
        $form.data("bootstrapValidator").validate();
        return $form.data("bootstrapValidator").isValid();
    }

    /**
     * 表单验证初始化
     * @private
     */
    function _initFormValidate(flag) {
        $("#vAddApplyForm").bootstrapValidator({
            live: 'enabled',
            excluded: [':hidden', ':not(:visible)'],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                vApplyName: {validators: {notEmpty:{message:"请输入资金计划批次"}}}/*,
                vSubjectName2: {validators: {notEmpty:{message:"请选择实施项目"}}}*/
                ,
                statusCd: {
                    validators: {
                        notEmpty: {
                            message: '状态不能为空'
                        }
                    }
                }
                ,
                yearDt: {
                    validators: {
                        notEmpty: {
                            message: '年份不能为空'
                        }
                    }
                }
                ,
                endDt: {
                    validators: {
                        notEmpty: {
                            message: '截止时间不能为空'
                        }
                    }
                }
            }
        });

        if(flag == undefined) {
            $('#addEditModal').on('hidden.bs.modal', function () {
                $('#vAddApplyForm').data('bootstrapValidator').destroy();
                $('#vAddApplyForm').data('bootstrapValidator', null);
                _initFormValidate("again");
            });
        }
    }

    /**
     * 资金计划列表查询
     * @param page
     * @param needTurn
     * @private
     */
    function _queryMoneys(index) {
        if(com.im.moneyPlaneManage.moneyApply.moneyColumns == undefined) {
            com.im.moneyPlaneManage.moneyApply.moneyColumns = [
                [{field:'全选',title:"全选",width:30,checkbox:true,fitColumns:true},
                    {field:'序号',title:"序号",width:25,fitColumns:true,
                        formatter: function(value,row,index){
                            return  index+1;
                        }
                    },
                    {field:'yearDt',title:"年份",width:50,fitColumns:true,align:'center'},
                    {field:'fundPlanCode',title:"资金计划申报编码",width:150,fitColumns:true},
                    {field:'fundPlanName',title:"资金计划申报批次",width:100,fitColumns:true},
                    //{field:'impleProjName',title:"实施项目名称",width:100,fitColumns:true},
                    {field:'endDt',title:"截止时间",width:80,fitColumns:true},
                    {field:'description',title:"备注",width:100,fitColumns:true,formatter: function(value,row,index){
                        if(value.length > 10){
                            return value.substr(0,10) + "...";
                        }else{
                            return value;
                        }
                    }},
                    {field:'statusName',title:"状态",width:80,fitColumns:true},
            	    {field:'operation',title:"操作",width:100,align:'center',
            	        formatter: function(value,row,index){
            	            return  '<a href="javascript:; "onclick="com.im.moneyPlaneManage.moneyApply.invoke.modMoneyApply(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a> '+
            	                    '<a href="javascript:; "onclick="com.im.moneyPlaneManage.moneyApply.invoke.delMoneyApply(\''+index+'\')" title="删除"><i class="fa fa-trash"></i></a>';
            	        }
            	    }
            	]]
        }
        var req = {};
        req.pageInfo = {};
        req.pageInfo.pageNumber = index;
        req.pageInfo.pageSize = 20;
        //req.impleProjName = $("#vSubjectName").val();
        req.fundPlanName = $("#vMoneyName").val();
        var resp = client.callAsJson("fundPlanService/queryFundPlanSetList", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

        $("#vMoneyTable").empty();
        $("#vMoneyTable").datagrid({
            nowrap:false,
            fitColumns:true,
            pagination:true,
            columns:com.im.moneyPlaneManage.moneyApply.moneyColumns,
            data:resp.result
        });
        var p = $('#vMoneyTable').datagrid('getPager');
        $(p).pagination({
            pageSize: 20,
            pageList: [10,20,30],
            beforePageText: '第',
            afterPageText: '页    共 {pages}  页',
            displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
            onSelectPage:function(pageNumber, pageSize){
                _queryMoneys(pageNumber);
            }
        });
    }

    /**
     * 条件重置
     * @private
     */
    function _resetCond() {
        $("#vSubjectName").val("");
        $("#vMoneyName").val("");
        _queryMoneys(1);
    }
    function _showAddMoney() {
    	var result = client.callAsJson("commonService/getSeq", {'tableName':'T_FUND_PLAN'});
   	    $("#vApplyCode").val(result.result.seq);
   	    $('#vSubjectName2').attr({'projectid':'','vasubjectid':''});
        $("#vApplyName").val("");
    	$("#declareSetId").val("");
    	$("#fundPlanId").val("");
        $("#vSubjectName2").val("");
        $("#vRemark").val("");
        $("#addEditModal").modal("show");
        $("#yearDt").val("");
        $("#endDt").val("");
    }

    /**
     * 资金计划申报
     * @private
     */
    function _addApply() {
        if(!_formValidate($("#vAddApplyForm"))) {
            return;
        }
        var req = {};
        req.fundPlanCode = $("#vApplyCode").val();
        req.fundPlanName = $("#vApplyName").val();
        req.fundPlanId = $("#fundPlanId").val();
        req.impleProjId = $("#vSubjectName2").attr("vaSubjectId");
        req.statusCd = $("#vState option:selected").attr('statusCdId');
        req.yearDt = $("#yearDt").val()+'-01-01';
        req.endDt = $("#endDt").val();
        req.description = com.im.common.util.escapeTextArea($("#vRemark").val());
	   	 var declareSetId= $("#declareSetId").val();
		 if(declareSetId!=''){
			 req.declareSetId= declareSetId;
		 }
		 req.enterRequest = $("#enterRequest").val() == '' ? '开放填报' : $("#enterRequest").val();//新增时enterRequest、docCode暂时给固定值
		 req.docCode = $("#docCode").val() == '' ? 'ios-10000' : $("#docCode").val();
    	 if(declareSetId!=''){
    		 var result = client.callAsJson("fundPlanService/updateFundPlanDeclareSet", req);
    		 if(result.resultCode=='0'){
    			 toastr.success("资金计划修改成功");
    		     _queryMoneys(1);
    		     $("#addEditModal").modal("hide");
    		 }else {
                 toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
             }
    	 }else{
    		 req.docCode='IOS-999999';
    		 req.enterRequest='填报要求';
    		 var result = client.callAsJson("fundPlanService/addFundPlanDeclareSet", req);
    		 if(result.resultCode=='0'){
    			 toastr.success("资金计划申报成功");
    		     _queryMoneys(1);
    		     $("#addEditModal").modal("hide");
    		 }else {
                 toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
             } 
    	 }	
        
    }
    //编辑
    function _modMoneyApply(index){
    	var req = $('#vMoneyTable').datagrid('getData').rows[index];
        // var result = client.callAsJson("fundPlanService/queryFundPlanSetDetail", {'declareSetId':row.declareSetId});
        // if (result.resultCode=="0") {
        //     if(result.result!= null){
        //     	var req = result.result;
        //     	$("#vApplyCode").val(req.fundPlanCode);
        //     	$("#fundPlanId").val(req.declareRelaObj);
        //     	$("#vApplyName").val(req.fundPlanName);
        //     	$("#declareSetId").val(req.declareSetId);
        //         $("#vSubjectName2").val(req.impleProjName).attr('vaSubjectId',req.impleProjId);
        //         $("#vRemark").val(req.description);
        //         $("#yearDt").val(req.yearDt);
        //         $("#endDt").val(req.endDt);
        //         $("#vState").val($("#vState option[statusCdId='"+req.statusCd+"']").html()).trigger("change");
        //         $("#addEditModal").modal("show");
        //     }
        // } else {
        //     toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        // }
        $("#vApplyCode").val(req.fundPlanCode);
        $("#fundPlanId").val(req.declareRelaObj);
        $("#vApplyName").val(req.fundPlanName);
        $("#declareSetId").val(req.declareSetId);
        $("#vSubjectName2").val(req.impleProjName).attr('vaSubjectId',req.impleProjId);
        $("#vRemark").val(req.description);
        $("#yearDt").val(req.yearDt);
        $("#endDt").val(req.endDt);
        $("#vState").val($("#vState option[statusCdId='"+req.statusCd+"']").html()).trigger("change");
        $("#addEditModal").modal("show");
    }
    //删除
    function _delMoneyApply(index){
    	var row = $('#vMoneyTable').datagrid('getData').rows[index];
    	com.im.common.confirm("确认是否删除", null, function () {
            if(row.statusCd != '10') {
                toastr.error("只允许删除【开放填报】资金计划");
                return;
            }
            var result = client.callAsJson("fundPlanService/updateFundPlanDeclareSet", {'declareSetId':row.declareSetId,'statusCd':'30'});
      	  	if (result.resultCode=="0") {
  		      toastr.success("删除成功！");
  		      _queryMoneys(1);
            } else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        });
    }
    return {
        init : _init,
		delMoneyApply : _delMoneyApply,
        modMoneyApply : _modMoneyApply
    }
}();